package com.fruit.interceptor;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.TreeMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fruit.util.CustomUtil;
import com.fruit.util.ResultInfo;
import com.fruit.util.ResultUtil;

/**
 * app签名Interceptor
 * @author shibeilei
 * @version 2017.11.30 12:20
 */
public class AppSecurityInterceptor extends HandlerInterceptorAdapter {

	@Value("${app.key}")
	private String key;

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		response.setContentType("text/html;charset=UTF-8");
		Map<String, Object> resMap = new HashMap<String, Object>();
		ObjectMapper om = new ObjectMapper();
		try {

			Map<String, String> paramsO = new TreeMap<String, String>();
			Map<?, ?> requestParams = request.getParameterMap();
			if (requestParams != null && requestParams.size() > 0) {
				for (Iterator<?> iter = requestParams.keySet().iterator(); iter.hasNext();) {
					String name = (String) iter.next();
					String[] values = (String[]) requestParams.get(name);
					String valueStr = "";
					for (int i = 0; i < values.length; i++) {
						// valueStr = (i == values.length - 1) ? valueStr +
						// values[i] : valueStr + values[i] + ",";
						if (i == values.length - 1) {
							valueStr = valueStr + values[i];
						} else {
							valueStr = valueStr + values[i] + ",";
						}
					}
					paramsO.put(name, valueStr);
				}
			}

			/*
			 * 验证 Long timestamp = Long.parseLong(paramsO.get("timestamp"));
			 * long period = System.currentTimeMillis() - timestamp; SysConfig
			 * sc = sysService.getSysConfigList().get(0); if(period >
			 * sc.getDiffTime()){ resMap.put("result",
			 * ResultUtil.initResult(ResultInfo.ERROR, "timeout", "连接超时"));
			 * response.getWriter().print(om.writeValueAsString(resMap)); return
			 * false; }
			 */

			String sign = paramsO.get("sign");
			if (StringUtils.isNotEmpty(sign)) {
				String mySign = CustomUtil.createSign(paramsO, key);
				if (StringUtils.equals(sign.toUpperCase(), mySign)) {
					return true;
				}

			}
			return false;
		} catch (Exception e) {
			e.printStackTrace();
			response.getWriter().print("exception");
			resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "exception", "系统异常"));
			response.getWriter().print(om.writeValueAsString(resMap));
			return false;
		}
	}
}
